#!/bin/bash

# CVE Advanced Taxonomy Query Runner Script  
# This script demonstrates how to use external taxonomy JSON files for enhanced display names
# The main jq_query.sh script runs all queries with the data available in cve.json
# This script is optional and shows how queries would work with external taxonomy files

set -e

CVE_FILE="cve.json"

# Check if cve.json exists
if [[ ! -f "$CVE_FILE" ]]; then
    echo "Error: $CVE_FILE not found in current directory"
    exit 1
fi

echo "Running enhanced CVE taxonomy queries with external files"
echo "========================================================"
echo "This script uses taxonomy integration queries that require external JSON files"
echo "for enhanced display names: severity.json, platforms.json, products.json"
echo

# Check if required taxonomy files exist  
if [[ ! -f "severity.json" ]]; then
    echo "Error: severity.json not found in current directory"
    exit 1
fi

if [[ ! -f "platforms.json" ]]; then
    echo "Error: platforms.json not found in current directory"
    exit 1
fi

if [[ ! -f "products.json" ]]; then
    echo "Error: products.json not found in current directory"
    exit 1
fi

echo "✅ Using existing taxonomy files: severity.json, platforms.json, products.json"

echo

echo "=== PLATFORM-SPECIFIC ANALYSIS ==="

echo
echo "--- cves_by_platform ---"
jq -r --slurpfile platforms platforms.json '
($platforms[0].items | map({(.string): .display_name}) | add) as $platform_names |
(["| CVE ID        | Platforms |",
  "| ------------- | --------- |"] +
 [.cves[] | 
  "| \(.id)  | \((.platforms | map($platform_names[.] // .)) | join(", ")) |"]) | 
.[]' "$CVE_FILE"

echo
echo "=== RISK ASSESSMENT ==="

echo
echo "--- cves_with_release_impact ---"
jq -r --slurpfile severity severity.json '
. as $root |
($severity[0].items | map({(.string): .display_name}) | add) as $severity_names |
(["| CVE ID        | Severity | Releases | Problem |",
  "| ------------- | -------- | -------- | ------- |"] +
 [$root.cves[] | 
  .id as $cve | 
  "| \($cve)  | \($severity_names[.severity] // .severity) | \(($root.cve_releases[$cve] // []) | join(", "))     | \(.problem) |"]) | 
.[]' "$CVE_FILE"


echo
echo "=== COMPONENT ANALYSIS ==="

echo  
echo "--- product_report_with_names ---"
jq -r --slurpfile products products.json '
($products[0].items | map({(.string): .display_name}) | add) as $product_names |
(["| Product | CVEs |",
  "| ------- | ---- |"] +
 [.product_cves | to_entries[] |
  "| \($product_names[.key] // .key) | \(.value | length) |"]) |
.[]' "$CVE_FILE"

echo
echo "========================================"
echo "✅ Taxonomy queries completed using existing files!"